<template>
  <div>
    <div>
      <el-row :gutter="10" justify="space-between">
        <el-col
          :xl="16"
          :lg="currentType === 1 ? 16 : 24"
          :md="24"
          :sm="24"
          :xs="24"
          class="mb-5px"
        >
          <div>
            <div class="bg">
              <div class="ml-16% pt-18px pb-4px"
                >{{ userName }}<span class="ml-10px mr-1px">您好！</span>祝您开心每一天</div
              >
              <div class="ml-16% text-16px"
                >登录于<span class="ml-10px">
                  {{ loginTime }}
                </span></div
              >
            </div>
            <el-row :gutter="10" justify="space-between">
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="h-250px mt-5px">
                  <div class="contract">
                    <div class="flex items-center justify-between">
                      <div>合同汇总</div>
                      <!-- <el-button link type="primary" class="todo_center" @click="goMyNum">
                        <div class="text-18px text-#256AF5">详情</div>
                      </el-button> -->
                    </div>
                    <el-statistic :value="outputTotal" class="total_number" />
                    <div class="lh-24px">
                      <div
                        >已项目移交<span class="ml-20px"
                          >{{ totalList.project_transfer }}个</span
                        ></div
                      >
                      <div class="my-10px"
                        >已项目开工<span class="ml-20px"
                          >{{ totalList.project_startup }}个</span
                        ></div
                      >
                      <div
                        >已项目交付<span class="ml-20px"
                          >{{ totalList.project_delivery }}个</span
                        ></div
                      >
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="h-250px mt-5px">
                  <div class="contract">
                    <div>今年项目总数</div>
                    <el-statistic :value="outputProjectNum" class="project_number" />
                    <div class="lh-24px">
                      <div class="flex items-center justify-between">
                        <div>今年项目总数</div>
                        <div>{{ projectNumber.thisYearProjectNumber }}个</div>
                      </div>
                      <div class="flex items-center justify-between mt-6px mb-8px">
                        <div>去年项目总数</div>
                        <div>{{ projectNumber.lastYearProjectNumber }}个</div>
                      </div>
                      <el-divider style="margin: 4px 0" />
                      <div class="flex items-center justify-between">
                        <div>今年较往年增长</div>
                        <div
                          ><span class="text-#CC352F">{{ projectNumber.growthNumber }}</span
                          >个</div
                        >
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
                <el-card shadow="hover" class="h-250px mt-5px">
                  <div class="contract">
                    <div class="mb-10px">今年项目总额（万元）</div>
                    <div class="flex text-34px text-#101010 lh-30px"
                      ><span class="mr-6px">¥ </span>
                      <el-statistic
                        :value="outputProjectAmount"
                        :precision="1"
                        class="project_number"
                    /></div>

                    <Echart :options="barProjectData" :height="85" />
                    <div class="lh-24px">
                      <div class="flex items-center justify-between">
                        <div>去年项目总额</div>
                        <div>￥{{ projectNumber.lastYearProjectAmount }}(万元)</div>
                      </div>
                      <el-divider style="margin: 4px 0" />
                      <div class="flex items-center justify-between">
                        <div>今年较往年增长</div>
                        <div
                          ><span class="text-#CC352F">{{ projectNumber.growthAmount }}</span
                          >(万元)</div
                        >
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :xl="8" :lg="currentType === 1 ? 8 : 24" :md="24" :sm="24" :xs="24">
          <el-card shadow="hover" class="h-350px">
            <div class="flex items-center justify-between">
              <el-button link style="padding: 0px; margin-left: -6px">
                <img class="mr-8px w-36px h-36px" src="@/assets/imgs/home/risk.png" />
                <div class="text-20px text-#000000">项目风险</div>
              </el-button>
              <el-button link type="primary" class="todo_center" @click="goMyRisk">
                <div class="text-18px text-#256AF5">更多</div>
              </el-button>
            </div>
            <Echart :options="pieRiskData" :height="150" />
            <el-table
              :data="riskList"
              v-loading="loading"
              empty-text="暂无风险记录"
              element-loading-text="Loading..."
              stripe
              :header-cell-style="{ background: '#E1EBFF', color: '#606266' }"
              show-overflow-tooltip
              max-height="120"
            >
              <el-table-column align="center" label="序号" type="index" width="70" />
              <el-table-column align="center" label="项目名称" prop="projectName" min-width="180" />
              <el-table-column
                align="center"
                label="交付经理"
                prop="projectManagerName"
                min-width="120"
              />
              <el-table-column align="center" label="操作" fixed="right" min-width="80">
                <template #default="scope">
                  <el-button link type="primary" @click="handleAudit(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="pt-5px">
      <el-row :gutter="10" justify="space-between">
        <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24">
          <el-card shadow="hover" class="mb-8px h-500px">
            <div class="flex items-center justify-between">
              <el-button link style="padding: 0px; margin-left: -6px">
                <img class="mr-8px w-36px h-36px" src="@/assets/imgs/home/todo.png" />
                <div
                  class="text-20px text-#6C6C6C"
                  :class="{ todo_btn: typeChecked }"
                  :checked="typeChecked"
                  @click="getTodoChange"
                  >我的待办任务</div
                >
                <div
                  class="text-20px text-#6C6C6C ml-30px"
                  :class="{ todo_btn: !typeChecked }"
                  :checked="!typeChecked"
                  @click="getToreadChange"
                  >我的待阅任务</div
                >
              </el-button>
              <el-button
                link
                type="primary"
                class="todo_center"
                @click="typeChecked ? goMyTodo() : goMyToread()"
              >
                <div class="text-18px text-#256AF5"> 更多 </div>
              </el-button>
            </div>
            <el-divider style="margin: 10px 0" />
            <div v-if="typeChecked">
              <el-table
                :data="myTodo"
                max-height="400"
                :row-height="60"
                v-loading="todoLoading"
                empty-text="暂无待办记录"
                element-loading-text="Loading..."
                stripe
                show-overflow-tooltip
              >
                <el-table-column
                  align="center"
                  label="项目名称"
                  prop="project_name"
                  min-width="200"
                >
                  <template #default="{ row }">
                    {{ !row.project_name ? '--' : row.project_name }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="流程阶段"
                  prop="process_instance.name"
                  min-width="140"
                >
                  <template #default="scope">
                    <div class="flex justify-center">
                      <el-tag effect="light">{{ scope.row.process_instance.name }} </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="当前任务"
                  prop="name"
                  min-width="180"
                >
                  <template #default="scope">
                    <div class="flex justify-center">
                      <el-tag effect="light">{{ scope.row.name }} </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="发起人"
                  prop="process_instance.startUser.nickname"
                />
                <el-table-column align="center" label="操作" fixed="right" min-width="80">
                  <template #default="scope">
                    <el-button link type="primary" @click="handleTodo(scope.row)">办理</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
              <div v-if="myToread.length != 0 && todoLoading === false" class="knowledge_list">
                <div
                  class="mt-20px text-16px text-#6C6C6C toRead_cont"
                  v-for="(item, index) in myToread"
                  :key="index"
                  @click="goToreadDetail(item)"
                >
                  <div class="flex items-center justify-between">
                    <div
                      class="flex items-center my-10px text-16px"
                      style="position: relative; flex: 1 1"
                    >
                      <div class="text-#256AF5 data_tag mr-4px">{{ item.templateCode }}</div>
                      <div class="todo_title knowledge_name" :title="item.templateContent">{{
                        item.templateContent
                      }}</div></div
                    >
                    <div class="text-16px text-#8C8C8C mx-5px">
                      {{ formatTime(item.createTime, 'yyyy-MM-dd HH:mm:ss') }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="myToread.length === 0 && todoLoading === false">
                <el-empty style="padding: 70px 0" description="暂无待阅" />
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
          <el-card shadow="hover" class="h-500px">
            <div class="flex items-center justify-between mb-10px">
              <el-button link style="padding: 0px; margin-left: -6px">
                <img class="mr-8px w-36px h-36px" src="@/assets/imgs/home/knowledge.png" />
                <div class="text-20px text-#000000">知识库上新</div>
              </el-button>
              <!-- <el-button link type="primary" @click="goFileList">
                <div class="text-18px text-#256AF5"> 更多 </div></el-button
              > -->
            </div>
            <el-skeleton v-if="loading === true" :rows="5" animated />
            <div v-if="knowledgeList.length != 0 && loading === false" class="knowledge_list">
              <div
                class="knowledge_style"
                v-for="(item, index) in knowledgeList"
                :key="index"
                @click="item.knowledgeType === 'CaseLibrary' ? goCaseList() : goFileList()"
              >
                <div class="flex items-center my-10px">
                  <div></div>
                  <div>{{ formatTime(item.createTime, 'yyyy年MM月dd日') }}</div>
                </div>
                <div class="knowledge_cont flex items-center justify-between px-14px">
                  <div class="mr-10px" style="flex: 1 1">
                    <div class="flex text-16px c-black mb-10px">
                      <div class="knowledge_tag">
                        <div v-if="item.knowledgeType === 'CaseLibrary'">案例库</div>
                        <div v-else>制度库</div>
                      </div>
                      <div class="knowledge_name" :title="item.name" style="flex: 1 1">{{
                        item.name
                      }}</div>
                    </div>
                    <div class="text-14px text-#6c6c6c">
                      <div class="mr-20px">发布人：{{ item.creator }}</div>
                    </div>
                  </div>
                  <el-image
                    class="w-60px h-50px"
                    style="border-radius: 4px"
                    :src="imgList[index].img_url"
                  />
                </div>
              </div>
            </div>
            <div v-if="knowledgeList.length === 0 && loading === false">
              <el-empty style="padding: 70px 0" description="暂无内容" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 表单弹窗：详情 -->
    <MyNotifyMessageDetail @action-completed="getMyToread" ref="noticeDetailRef" />
  </div>
</template>
<script lang="ts" setup>
import { getUserProfile } from '@/api/system/user/profile'
import * as NotifyMessageApi from '@/api/system/notify/message'
import * as KmsApi from '@/api/project/kms'
import * as IctApi from '@/api/project/ict'
import * as BpmApi from '@/api/project/bpm'
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'
import { barTimeOptions, pieRegionOptions } from './echarts-data'
import MyNotifyMessageDetail from './Detail.vue'
import { useTransition } from '@vueuse/core'
import dayjs from 'dayjs'
import homeImg1 from '@/assets/imgs/home/imgList/1.png'
import homeImg2 from '@/assets/imgs/home/imgList/2.png'
import homeImg3 from '@/assets/imgs/home/imgList/3.png'
import homeImg4 from '@/assets/imgs/home/imgList/4.png'
import homeImg5 from '@/assets/imgs/home/imgList/5.png'
import homeImg6 from '@/assets/imgs/home/imgList/6.png'
import homeImg7 from '@/assets/imgs/home/imgList/7.png'
import homeImg8 from '@/assets/imgs/home/imgList/8.png'
import homeImg9 from '@/assets/imgs/home/imgList/9.png'
import homeImg10 from '@/assets/imgs/home/imgList/10.png'

const { push } = useRouter()
const userName = ref('')
const loginTime = ref('')
const loading = ref(true) // 列表的加载中
const todoLoading = ref(true) // 待办加载

// 监听屏幕尺寸
const currentType = ref()
const handleResize = () => {
  // 获取当前窗口的宽度（屏幕尺寸）
  const windowSize = window.innerWidth
  if (windowSize >= 1400) {
    currentType.value = 1
  } else {
    currentType.value = 2
  }
}
// 监听窗口大小变化事件
window.addEventListener('resize', handleResize)
window.dispatchEvent(new Event('resize'))

//获取用户信息
const getUser = async () => {
  await getUserProfile().then((res) => {
    userName.value = res.nickname
    loginTime.value = dayjs(res.loginDate).format('YYYY年-MM-DD A hh:mm')
  })
}

// 查询合同汇总数据
const totalNum = ref(0)
const outputTotal = useTransition(totalNum, {
  duration: 1000
})

const totalList = ref([]) // 合同汇总数据
const getTotalData = async () => {
  await IctApi.getTotalData()
    .then((res) => {
      totalList.value = res
      totalNum.value = res.sum
    })
    .catch(() => {})
}

// 跳转合同汇总详情
// const goMyNum = () => {
//   push({
//     name: 'MyTodo'
//   })
// }

// 项目数量金额统计数据
const projectNum = ref(0)
const outputProjectNum = useTransition(projectNum, {
  duration: 1000
})

const projectAmount = ref(0)
const outputProjectAmount = useTransition(projectAmount, {
  duration: 1000
})
const projectNumber = ref({}) // 项目总数据
const barProjectList = ref([]) //已结项总额折线图数据
const getProjectNumberData = async () => {
  try {
    const data = await IctApi.getProjectNumber()
    projectNumber.value = data
    projectNum.value = Number(data.thisYearProjectNumber)
    projectAmount.value = Number(data.thisYearProjectAmount)
    barProjectList.value = []
    const currentYear = new Date().getFullYear()
    for (let year = currentYear - 4; year <= currentYear; year++) {
      let value = 0
      if (year === currentYear) {
        // 今年金额
        value = parseFloat(data.thisYearProjectAmount)
      } else if (year === currentYear - 1) {
        // 去年金额
        value = parseFloat(data.lastYearProjectAmount)
      }
      barProjectList.value.push({
        value: value,
        name: String(year)
      })
    }
    getBarProjectList()
  } catch {}
}

//项目数量金额统计折线图
const barProjectData = reactive<EChartsOption>(barTimeOptions) as EChartsOption
const getBarProjectList = async () => {
  barProjectData!.series![0].data = barProjectList.value.map((v) => {
    return {
      name: v.name,
      value: v.value
    }
  })
}

// 风险类型映射
const riskObj = {
  timely_transfer_risk: '未及时交底风险',
  timely_team_risk: '未及时团队组建风险',
  timely_delivery_risk: '未及时交付风险'
}

// 获取风险数量统计数据
const pieRiskList = ref([]) //风险饼图数据
const getRiskData = async () => {
  try {
    const data = await IctApi.getRiskData()
    pieRiskList.value = []
    for (const key in riskObj) {
      if (riskObj.hasOwnProperty(key)) {
        pieRiskList.value.push({
          name: riskObj[key],
          value: data[key]
        })
      }
    }
    getPieRiskList()
  } catch {}
}

//风险数量统计饼图
const pieRiskData = reactive<EChartsOption>(pieRegionOptions) as EChartsOption
const getPieRiskList = async () => {
  pieRiskData!.series![0].data = pieRiskList.value.map((v) => {
    return {
      name: v.name,
      value: v.value
    }
  })
  set(pieRiskData, 'legend', {
    type: 'scroll',
    orient: 'vertical',
    right: '10%',
    top: '30%',
    itemGap: 10,
    formatter: (name) => {
      const item = pieRiskList.value.find((v) => v.name === name)
      return `${name}: ${item ? item.value : '0'}`
    },
    textStyle: {
      fontSize: 14
    }
  })
}

// 跳转风险清单
const goMyRisk = () => {
  push({
    name: 'RiskList'
  })
}

// 查询风险清单列表
const riskList = ref([]) // 风险列表的数据
const getRiskList = async () => {
  const params = {
    pageNo: 1,
    pageSize: 3,
    projectCode: '',
    type: '',
    status: 'unReleased'
  }
  IctApi.getRiskPage(params)
    .then((res) => {
      let data = res.list
      riskList.value = data
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 处理审批按钮跳转项目移交详情
const handleAudit = (row: any) => {
  push({
    name: 'ProjectDetails',
    query: {
      project_code: row.projectCode
    }
  })
}

//点击切换待办
const typeChecked = ref(true)
const isLosk = ref(true)
const myTodo = ref([])
const myToread = ref([])
const getTodoChange = () => {
  typeChecked.value = true
  if (isLosk.value) {
    getMyTodo()
    isLosk.value = false
  }
}

//点击切换待阅
const getToreadChange = () => {
  typeChecked.value = false
  todoLoading.value = true
  if (!isLosk.value) {
    getMyToread()
    isLosk.value = true
  }
}

//获取待办列表
const getMyTodo = async () => {
  myTodo.value = []
  return new Promise<void>((resolve, reject) => {
    BpmApi.getMytodoList()
      .then((res: { list: any }) => {
        const data = res.list
        todoLoading.value = false
        const projectList = ref([])
        data.forEach((item: { process_instance: { businessKey: any } }) => {
          const projectCode = item.process_instance.businessKey.split('+')[0]
          projectList.value.push(projectCode)
        })
        if (projectList.value.length > 0) {
          // 批量获取项目名称
          const projectsData = {
            project_codes: [...projectList.value]
          }
          KmsApi.getProjectsByList(projectsData)
            .then((res) => {
              let newdata = res
              data.forEach(
                (item: {
                  process_instance: { businessKey: string | number; name: any }
                  project_name: any
                }) => {
                  const projectCode = item.process_instance.businessKey.split('+')[0]
                  if (newdata[projectCode]) {
                    item.project_code = projectCode
                    item.project_name = newdata[projectCode].project_name
                  }
                }
              )
              myTodo.value = data
              resolve()
            })
            .catch((error) => {
              reject(error)
            })
        }
      })
      .catch((error) => {
        todoLoading.value = false
        reject(error)
      })
  })
}

// 待办处理
const handleTodo = (row) => {
  if (row.process_instance.name === '项目变更') {
    push({
      name: 'ProjectChangeApproval',
      query: {
        project_code: row.process_instance.businessKey.split('+')[0],
        change_key: row.process_instance.businessKey.split('+')[1],
        process_instance_id: row.process_instance_id
      }
    })
  } else {
    push({
      name: 'ProjectDetails',
      query: {
        project_code: row.process_instance.businessKey
      }
    })
  }
}

// 获取我的待阅
const getMyToread = async () => {
  myToread.value = []
  const params = {
    pageNo: 1,
    pageSize: 10,
    readStatus: 0,
    createTime: []
  }
  const res = await NotifyMessageApi.getIctMyNotifyMessagePage(params)
  myToread.value = res.list
  todoLoading.value = false
}

// 跳转待阅详情
const noticeDetailRef = ref()
const goToreadDetail = (code: any) => {
  noticeDetailRef.value.open(code)
}

// 跳转我的待办
const goMyTodo = () => {
  push({
    name: 'MyTodo'
  })
}

// 跳转我的待阅
const goMyToread = () => {
  push({
    name: 'MyToread'
  })
}

//获取知识库上新
const knowledgeList = ref([]) // 知识库的数据
const getKnowledgeList = async () => {
  IctApi.getKnowledgeNew()
    .then((res) => {
      knowledgeList.value = res
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 制度库上新图片
const imgList = [
  // {
  //   img_url: 'http://localhost/src/assets/imgs/home/imgList/2.png'
  // },
  {
    img_url: homeImg1
  },
  {
    img_url: homeImg2
  },
  {
    img_url: homeImg3
  },
  {
    img_url: homeImg4
  },
  {
    img_url: homeImg5
  },
  {
    img_url: homeImg6
  },
  {
    img_url: homeImg7
  },
  {
    img_url: homeImg8
  },
  {
    img_url: homeImg9
  },
  {
    img_url: homeImg10
  }
]

// 跳转制度库
const goFileList = () => {
  push({
    name: 'FileList'
  })
}

// 跳转按理库
const goCaseList = () => {
  push({
    name: 'CasePresentation'
  })
}

// 初始化
onMounted(() => {
  handleResize()
  getUser()
  getTotalData()
  getProjectNumberData()
  getRiskData()
  getRiskList()
  getTodoChange()
  getKnowledgeList()
})
</script>
<style scoped>
.bg {
  width: 100%;
  height: 90px;
  margin-bottom: 5px;
  background: url(/@/assets/imgs/home/bg.png) no-repeat;
  background-size: 100% 100%;
  color: rgba(255, 255, 255, 1);
  font-size: 20px;
  border-radius: 4px;
}

.contract {
  color: rgba(140, 140, 140, 1);
  font-size: 16px;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  height: 210px;
}

.todo_title {
  position: relative;
  height: 26px;
  line-height: 26px;
  flex: 1 1;
  cursor: pointer;
}

.data_tag::after {
  content: '';
  width: 12px;
  height: 12px;
  border-radius: 50px;
  background: #fa9e3c;
  position: absolute;
  left: 5px;
  top: 7px;
}

.data_tag {
  background-color: rgba(234, 241, 254, 1);
  color: rgba(74, 130, 249, 1);
  font-size: 14px;
  text-align: center;
  height: 26px;
  line-height: 25px;
  padding: 1px 5px;
  margin-left: 23px;
}

.knowledge_tag {
  background-color: rgba(234, 241, 254, 1);
  color: rgba(74, 130, 249, 1);
  font-size: 14px;
  text-align: center;
  padding: 1px 3px;
  margin-right: 5px;
}

.toRead_cont:hover {
  background-color: rgba(74, 130, 249, 0.14);
}

.todo_btn {
  position: relative;
  color: #256af5;
}

.todo_btn::after {
  content: '';
  width: 117px;
  height: 2px;
  background: #256af5;
  position: absolute;
  bottom: -19px;
  left: 0;
}

.knowledge_list {
  height: 406px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 5px;
}

.knowledge_list > div:first-child {
  margin-top: 0px;
}

:deep(.knowledge_list)::-webkit-scrollbar {
  width: 6px;
}

:deep(.el-table) {
  font-size: 16px !important;
}

:deep(.knowledge_list):hover::-webkit-scrollbar-thumb {
  background: rgba(68, 68, 68, 0.1);
}

:deep(.knowledge_list)::-webkit-scrollbar-thumb {
  border-radius: 20px;
  background: transparent;
}

:deep(.knowledge_list)::-webkit-scrollbar-track {
  display: none;
}

.knowledge_style {
  color: #6c6c6c;
  font-size: 16px;
  margin-top: 20px;
  cursor: pointer;
}

.knowledge_style > div:first-child > div:first-child {
  width: 12px;
  height: 12px;
  border-radius: 50px;
  background: #256af5;
  margin-right: 10px;
}

.knowledge_cont {
  height: 85px;
  border-radius: 4px;
  background-color: rgba(248, 248, 248, 1);
}

.knowledge_name {
  overflow: hidden;
  display: -webkit-box;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

:deep(.total_number .el-statistic__number) {
  font-size: 28px;
  color: #101010;
  margin-bottom: 14px;
}
:deep(.project_number .el-statistic__number) {
  font-size: 34px;
  color: #101010;
}
</style>